﻿using System;
using System.Collections.Specialized;
using System.Net;
using Framework;

namespace Koala.JiraTool.Core
{
    internal class DefaultHttpClient : WebClient, IHttpClient
    {
        #region Field

        private CookieContainer _cookieContainer;
        private readonly GlobalSettings _globalSettings;

        #endregion Field

        #region Constructor

        public DefaultHttpClient(GlobalSettings globalSettings)
        {
            _globalSettings = globalSettings;
            _cookieContainer = new CookieContainer();
        }

        #endregion Constructor

        #region Override Method

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                var httpRequest = request as HttpWebRequest;
                httpRequest.CookieContainer = _cookieContainer;
            }
            return request;
        }

        #endregion Override Method

        #region Implementation of IHttpClient

        public string PostData(string address, NameValueCollection postData)
        {
            var data = UploadValues(address, "post", postData);
            return _globalSettings.Encoding.GetString(data);
        }

        public new string DownloadString(string address)
        {
            return _globalSettings.Encoding.GetString(DownloadData(address));
        }

        public void Reset()
        {
            _cookieContainer = new CookieContainer();
        }

        #endregion Implementation of IHttpClient
    }
}